package com.echo.im.repository.offline.support;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.echo.im.repository.dao.entity.OfflineMessage;
import com.echo.im.repository.dao.mapper.OfflineMessageMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 使用 MyBatis-Plus 实现的 MySQLMessageStorage，管理离线消息表中的 msgId 列表。
 * @author echo
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MySQLOfflineStorage {

    private final OfflineMessageMapper offlineMessageMapper;

    public List<String> getMessageIds(Long userId, Long lastFetchedMessageId, int size) {
        QueryWrapper<OfflineMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OfflineMessage::getUserId, userId)
                .gt(OfflineMessage::getMessageId, lastFetchedMessageId)
                .orderByAsc(OfflineMessage::getMessageId)
                .last("LIMIT " + size);
        List<OfflineMessage> offlineMessages = offlineMessageMapper.selectList(queryWrapper);
        return offlineMessages.stream()
                .map(OfflineMessage::getMessageId)
                .collect(Collectors.toList());
    }

    public void saveMessageIds(Long userId, List<String> msgIds) {
        List<OfflineMessage> messages = msgIds.stream()
                .map(msgId -> new OfflineMessage(msgId, userId))
                .collect(Collectors.toList());
        offlineMessageMapper.insert(messages);
    }

    public void deleteMessageIds(Long userId, Long lastFetchedMessageId) {
        QueryWrapper<OfflineMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OfflineMessage::getUserId, userId)
                .le(OfflineMessage::getMessageId, lastFetchedMessageId);
        offlineMessageMapper.delete(queryWrapper);
    }
}
